import ScrollBarLayout from '@/components/ScrollBarLayout';
import { TypographyTitle } from '@/components/Typography';
import { AutoComplete, Card, Empty, Input } from 'antd';
import React, { useCallback, useState } from 'react';
import cls from 'classnames';
import { SearchOutlined } from '@ant-design/icons';
import dataCard from '../../styles.less';
import { positionAPI } from '../../type';

export const OtherDetailInfo = React.forwardRef(
  (
    {
      infoType, //数据类型
      dataList, //数据
      titleIcon, //数组展示头部图标
    }: positionAPI.IOtherDetailInfo,
    ref,
  ) => {
    const prefixCard = 'update-othercard'; //组件内部样式
    const [seachValue, setSeachValue] = useState<string>(''); //保存右侧树搜索的值
    const [autoOption, setAutoOption] = useState<any[]>([]); //保存 AutoComplete 的下拉菜单值

    // 返回数据类型title
    const getDataTitle = () => {
      switch (infoType) {
        case 'duty':
          return '管辖信息';
        case 'roule':
          return '角色信息';
        case 'subject':
          return '科目信息';
        default:
          return '';
      }
    };

    // 左侧树 点击搜索
    const onAutoSelect = useCallback(
      (value: string, option: any, list: any[]) => {
        const optionId = option?.key;
        setSeachValue(value);
        // const targetNode = list?.find( (i) => i?.id === optionId, );

        // 滚动定位
        setTimeout(() => {
          scrollToAnchor(optionId);
        }, 1000);
      },
      [dataList],
    );

    // 左右两侧搜索框点击搜索
    const onSearch = useCallback(
      (e: React.ChangeEvent<HTMLInputElement>, list: any) => {
        const searchValue = e.target.value;
        setSeachValue(searchValue);
        const tileArray: Record<string, any>[] = list?.length > 0 ? list : [];

        if (searchValue && searchValue.length > 0) {
          const newOption: any[] = tileArray
            ?.map((item, index) => {
              if ((item?.name ?? item?.text)?.includes(searchValue)) {
                // const name = item?.name ?? item?.text;
                // const nameLength = name?.length;
                // const select = name?.search(searchValue);
                // const searchLength = searchValue?.length;
                // const afterStr = name?.slice(0, select);
                // const selectStr = searchValue;
                // const beforeStr = name?.slice(
                //   select + searchLength,
                //   nameLength,
                // );

                return {
                  value: item?.name ?? item?.text,
                  key: item?.id + infoType,
                  // label: (
                  //   <>
                  //     <span>{afterStr}</span>
                  //     <span style={{ color: '#f50' }}>{selectStr}</span>
                  //     <span>{beforeStr}</span>
                  //   </>
                  // ),
                };
              }
            })
            ?.filter((item) => typeof item !== 'undefined');
          setAutoOption(newOption);
        } else {
          setAutoOption([]);
        }
      },
      [autoOption],
    );

    // 滚动定位
    const scrollToAnchor = (id: string) => {
      let anchorElement = document.getElementById(id);
      if (id) {
        anchorElement?.scrollIntoView({
          behavior: 'smooth',
          block: 'nearest',
          inline: 'start',
        });
      }
    };

    // 处理搜索变色
    const searchChangeStyle = (dataName: string, icon?: any) => {
      const name = dataName;
      const nameLength = name?.length;
      const select = name?.search(seachValue);
      const searchLength = seachValue?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = seachValue;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const title =
        select > -1 && selectStr ? (
          <div>
            {icon}
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </div>
        ) : (
          <div>
            {icon}
            {dataName}
          </div>
        );
      return title;
    };

    return (
      <>
        <div style={{ padding: '15px 0px 10px 0px' }}>
          <TypographyTitle
            level={4}
            style={{
              margin: 0,
            }}
          >
            {getDataTitle()}
          </TypographyTitle>
        </div>
        <div className={cls(prefixCard)}>
          <Card
            bordered
            title={
              <>
                <AutoComplete
                  style={{ width: '100%' }}
                  options={autoOption}
                  notFoundContent={
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                  }
                  onSelect={(value: string, option: any) => {
                    onAutoSelect(value, option, dataList);
                  }}
                >
                  <Input
                    suffix={<SearchOutlined />}
                    onChange={(e) => {
                      onSearch(e, dataList);
                    }}
                    placeholder="请按名称搜索"
                    allowClear={true}
                  />
                </AutoComplete>
              </>
            }
          >
            <ScrollBarLayout
              style={{
                padding: '10px 10px',
                maxHeight: document.body.clientHeight * 0.3,
                minHeight: document.body.clientHeight * 0.2,
              }}
            >
              {dataList?.length > 0 ? (
                <div className={dataCard['detailCard']}>
                  {dataList?.map((item) => {
                    let showTitle = searchChangeStyle(item?.name, titleIcon);
                    return (
                      <div
                        className={dataCard['detailCardChild']}
                        id={item?.id + infoType}
                        key={item?.id + infoType}
                      >
                        <div>{showTitle}</div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
              )}
            </ScrollBarLayout>
          </Card>
        </div>
      </>
    );
  },
);
